﻿''
'' Copyright (c) 2010-2012, MatthiWare
''
'' Permission is hereby granted, free of charge, to any person obtaining a
'' copy of this software and associated documentation files (the "Software"),
'' to deal in the Software without restriction, including without limitation
'' the rights to use, copy, modify, merge, publish, distribute, sublicense,
'' and/or sell copies of the Software, and to permit persons to whom the
'' Software is furnished to do so, subject to the following conditions:
''
'' The above copyright notice and this permission notice shall be included in
'' all copies or substantial portions of the Software. 
'' You shall include 'MatthiWare' in the credits/about section of the program
''
'' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
'' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
'' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
'' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
'' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
'' FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
'' DEALINGS IN THE SOFTWARE.
''

'Imports System.Threading
'Imports System.IO
'Imports System.Diagnostics
'Imports System.Text
'Imports System.ComponentModel

'Public Class frmMain

'    Public fullscreen As Boolean
'    Public prevWindowState As FormWindowState = FormWindowState.Normal

'    Public Shared strTitle As String = "Matthiee's Game "
'    Public Shared strBy As String = " by MatthiWare!"

'    Public X As Int32
'    Public Y As Int32

'    Dim isGameRunning As Boolean

'    Dim isPaused As Boolean

'    Private Delegate Sub SetTitleCallback(ByVal strTitle As String)

'    Public cfgMgr As New ConfigManager(Of Cfg)
'    Public Shared fpsMonitor As New FpsMonitor()

'    Public config As New Cfg()

'    Public Running As Boolean = True

'    Public wrld As World

'    Public p As Player

'    Public reducedCpuUsage As Int32

'    Public Shared SmoothingMode As Drawing2D.SmoothingMode = Drawing2D.SmoothingMode.None

'    Private screen As Bitmap
'    Private screenBackBuffer As Bitmap
'    Private currPerc As Int32

'    Dim causedBy As String = "NULL"
'    Dim causedByTarget As String = "NULL"

'    Public showInv As Boolean = False

'    Public Shared Function GraphicsFromScreen() As Graphics
'        Return Graphics.FromImage(frmMain.Current.screen)
'    End Function

'    Private _requestedFrameMS As Single = (1 / 30)
'    Private _requestedFPS As Int32 = 30
'    Public Property RequestedFPS() As Int32
'        Get
'            Return _requestedFPS
'        End Get
'        Set(value As Int32)
'            _requestedFPS = value
'            _requestedFrameMS = 1 / value
'        End Set
'    End Property

'    Public Sub New()
'        ' This call is required by the designer.
'        InitializeComponent()

'        Try
'            Utils.UnsafeCheckPaths()
'        Catch ex As Exception
'            CreateErrorLog(ex)
'            MessageBox.Show("Some files/directories are missing or are corrupt" & vbNewLine & "View the log files for more info", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
'            Application.Exit()
'        End Try

'        AddHandler Me.MouseWheel, AddressOf MouseWheelScroll

'        Item.CreateDefaults()
'        NpcXmlInfo.CreateDefaults()

'        config = cfgMgr.Load(config)
'        'cfgMgr.Save(config)
'        World.WorldHeight = config.worldHeight
'        World.WorldWidth = config.worldWidth
'        reducedCpuUsage = config.reduceCpuUsage
'        Tile.TileSize = config.tileSize
'        IIf(config.antiAliasing, SmoothingMode = Drawing2D.SmoothingMode.HighQuality, SmoothingMode = Drawing2D.SmoothingMode.HighSpeed)

'        ' Add any initialization after the InitializeComponent() call.
'        wrld = New World()

'        Dim thrd As New Thread(New ThreadStart(AddressOf GameBootstrapper))
'        thrd.Name = "Game loop!"
'        thrd.Priority = ThreadPriority.Highest
'        thrd.Start()
'    End Sub

'    Public Sub SetTitle(strText As String)
'        If (InvokeRequired) Then
'            Dim cb As New SetTitleCallback(AddressOf SetTitle)
'            Me.Invoke(cb, strText)
'        Else
'            Me.Text = strText
'        End If
'    End Sub

'    Public Sub GameBootstrapper()
'        'Try
'        '    'CheckForIllegalCrossThreadCalls = False
'        '    ' Loads the tileset
'        '    Tile.LoadImage()

'        '    screen = New Bitmap(CInt((World.WorldWidth * Tile.TileSize)), CInt((World.WorldHeight * Tile.TileSize)))


'        '    p = New Player(New Point(Camera.Vision.Width / 2, 10), New Size(26, 46))

'        '    'Generating wrld
'        '    'wrld.GenerateWorld(config.seed)
'        '    wrld.GenerateWorldDebug()
'        '    'wrld.Save()


'        '    'p.inventory.slots(0, 0).Info.Stack = 1
'        '    'p.inventory.slots(0, 0).Info.Item = Item.LoadItem(1)
'        '    'p.inventory.slots(0, 0).Init()
'        '    'p.inventory.slots(1, 0).Info.Stack = 99
'        '    'p.inventory.slots(1, 0).Info.Item = Item.LoadItem(3)
'        '    'p.inventory.slots(1, 0).Init()
'        '    'p.inventory.slots(2, 0).Info.Stack = 1
'        '    'p.inventory.slots(2, 0).Info.Item = Item.LoadItem(4)
'        '    'p.inventory.slots(2, 0).Init()
'        '    'p.inventory.slots(3, 0).Info.Stack = 1
'        '    'p.inventory.slots(3, 0).Info.Item = Item.LoadItem(5)
'        '    'p.inventory.slots(3, 0).Init()
'        '    'p.inventory.slots(0, 1).Info.Stack = 99
'        '    'p.inventory.slots(0, 1).Info.Item = Item.LoadItem(3)
'        '    'p.inventory.slots(0, 1).Init()
'        '    'p.inventory.slots(4, 0).Info.Stack = 99
'        '    'p.inventory.slots(4, 0).Info.Item = Item.LoadItem(3)
'        '    'p.inventory.slots(4, 0).Init()

'        '    'World.CurrentWorld.SpawnItem(10, 1, 5)
'        '    'World.CurrentWorld.SpawnItem(20, 1, 6)
'        '    'World.CurrentWorld.SpawnItem(30, 1, 7)
'        '    'World.CurrentWorld.SpawnItem(40, 1, 8)
'        '    'World.CurrentWorld.SpawnItem(50, 1, 9)

'        '    'World.CurrentWorld.SpawnNpc(5, 10, 1)
'        '    'World.CurrentWorld.SpawnNpc(15, 10, 2)
'        '    World.CurrentWorld.SpawnNpc(25, 10, 3)

'        '    isGameRunning = True
'        '    Dim c As Boolean
'        '    While (Running)
'        '        Dim sw As New Stopwatch()
'        '        sw.Start()
'        '        Application.DoEvents()

'        '        If (Not isPaused) Then
'        '            Tick()
'        '            Render()
'        '        Else
'        '            DrawPauseString()
'        '        End If

'        '        If (reducedCpuUsage > 0) Then Thread.Sleep(reducedCpuUsage)

'        '        If (c) Then
'        '            fpsMonitor.Draw()
'        '        End If
'        '        c = Not c

'        '        While sw.Elapsed.TotalSeconds < _requestedFrameMS
'        '            System.Threading.Thread.SpinWait(10)
'        '        End While

'        '        sw.Stop()
'        '    End While

'        '    isGameRunning = False
'        'Catch ex As Exception
'        '    CreateErrorLog(ex)
'        '    isGameRunning = False
'        '    MessageBox.Show("Error occured while running the game." + vbNewLine + "look in at the log file for more info.", "Terraria VB runtime error", MessageBoxButtons.OK, MessageBoxIcon.Error)
'        'End Try

'    End Sub

'    Public Sub CreateErrorLog(e As Exception)

'        'afwerken
'        Dim exCurrent As Exception = e
'        Dim dte As Date = Date.Now()
'        Dim logStream As FileStream = File.Open(String.Format(".\Logs\Error_{0}-{1}-{2}.{3}-{4}-{5}.log", dte.Day, dte.Month, dte.Year, dte.Hour, dte.Minute, dte.Millisecond), FileMode.OpenOrCreate, FileAccess.Write)
'        Dim sbStack As New StringBuilder()
'        Dim sbMessage As New StringBuilder()
'        Dim sbSource As New StringBuilder()
'        Dim sbTarget As New StringBuilder()

'        sbStack.AppendLine("Stack: ")
'        sbMessage.AppendLine("Message: ")
'        sbSource.AppendLine("Source: ")
'        sbTarget.AppendLine("Target: ")

'        Do Until IsNothing(exCurrent)
'            If (Not IsNothing(exCurrent.Message)) Then sbMessage.AppendLine(String.Format("{0:5}", exCurrent.Message))
'            If (Not IsNothing(exCurrent.Source)) Then sbSource.AppendLine(String.Format("{0:5}", exCurrent.Source))
'            If (Not IsNothing(exCurrent.TargetSite)) Then sbTarget.AppendLine(String.Format("{0:5}", exCurrent.TargetSite.ToString()))
'            If (Not IsNothing(exCurrent.StackTrace)) Then sbStack.AppendLine(String.Format("{0:5}", exCurrent.StackTrace))

'            If (Not IsNothing(exCurrent.Source)) Then causedBy = exCurrent.Source
'            If (Not IsNothing(exCurrent.TargetSite)) Then causedByTarget = exCurrent.TargetSite.ToString()

'            exCurrent = exCurrent.InnerException
'        Loop

'        Dim sw As New StreamWriter(logStream, Encoding.Default)
'        sw.WriteLine(sbMessage.ToString())
'        sw.WriteLine(sbSource.ToString())
'        sw.WriteLine(sbTarget.ToString())
'        sw.WriteLine(sbStack.ToString())

'        sw.Dispose()
'        logStream.Dispose()

'    End Sub

'    Public Sub Tick()
'        p.Tick(e)
'        wrld.Tick(e)
'        fpsMonitor.UpdateTPS()
'    End Sub

'    Public Sub Render()
'        Dim g As Graphics = GraphicsFromScreen()
'        g.SmoothingMode = frmMain.SmoothingMode

'        wrld.Render(g)

'        p.Render(g)
'        p.inventory.Render(g, showInv)

'        g = Me.CreateGraphics()
'        g.SmoothingMode = frmMain.SmoothingMode

'        g.DrawImage(screen, 0, 0)

'        g.Dispose()

'        fpsMonitor.UpdateFPS()

'    End Sub

'    Private Sub frmMain_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
'        Me.Running = False
'        Do Until isGameRunning = False
'            Application.DoEvents()
'            Thread.Sleep(5)
'        Loop
'    End Sub

'    Private Sub frmMain_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
'        If (isGameRunning) Then

'            If (e.KeyCode = Keys.D) Then
'                p.MoveDirection = TerrariaVB.Player.MoveDir.Right
'            ElseIf (e.KeyCode = Keys.Q) Then
'                p.MoveDirection = TerrariaVB.Player.MoveDir.Left
'            End If

'            If (e.KeyCode = Keys.Space) Then
'                If (Not p.jumpDown) Then
'                    p.jumpDown = True
'                    p.PrepareJump()
'                End If
'            End If

'            If (e.KeyCode = Keys.Escape) Then
'                showInv = Not showInv
'            End If

'            If (e.KeyCode = Keys.T) Then
'                p.TeleportTo(New Point(Camera.Vision.Width / 2, 10))
'            End If

'            If (e.KeyCode = Keys.P) Then
'                isPaused = Not isPaused
'            End If

'            If (e.KeyCode = Keys.F11) Then

'                If (fullscreen) Then
'                    Me.WindowState = prevWindowState
'                    Me.FormBorderStyle = Windows.Forms.FormBorderStyle.Sizable
'                Else
'                    prevWindowState = Me.WindowState
'                    Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
'                    Me.WindowState = FormWindowState.Maximized
'                End If

'                fullscreen = Not fullscreen
'            End If

'        End If
'    End Sub

'    Private Sub frmMain_KeyUp(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp
'        If (e.KeyCode = Keys.D) Then
'            p.MoveDirection = TerrariaVB.Player.MoveDir.None
'        ElseIf (e.KeyCode = Keys.Q) Then
'            p.MoveDirection = TerrariaVB.Player.MoveDir.None
'        End If

'        If (e.KeyCode = Keys.Space) Then
'            p.jumpDown = False
'        End If
'    End Sub

'    Private Sub DrawPauseString()
'        Thread.Sleep(100)
'        Dim g As Graphics = Me.CreateGraphics()
'        g.DrawString("GAME PAUSED", New Font("Comic Sans MS", 12, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.WhiteSmoke, New Point((Me.Width / 2) - 20, (Me.Height / 2)))
'        g.Dispose()
'    End Sub

'    Public Delegate Sub DrawGenStateCallback(ByVal strInf As String)
'    Public Sub DrawGenState(strInf As String)
'        If (Me.InvokeRequired) Then
'            Dim cb As New DrawGenStateCallback(AddressOf DrawGenState)
'            Me.Invoke(cb, strInf)
'        Else
'            Dim g As Graphics = GraphicsFromScreen()
'            g.Clear(Me.BackColor)
'            Dim f As New Font("Comic Sans MS", 15, FontStyle.Bold, GraphicsUnit.Pixel)
'            Dim b As Brush = Brushes.WhiteSmoke
'            Dim pt As New Point(Me.Width / 19, Me.Height / 19)
'            g.DrawString(strInf, f, b, pt)
'            g = Me.CreateGraphics()
'            g.DrawImage(screen, 0, 0)
'            g.Dispose()
'        End If
'    End Sub

'    Private Sub frmMain_MouseDown(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
'        If (e.Button = Windows.Forms.MouseButtons.Left) Then
'            p.leftMouseDown = True
'        ElseIf (e.Button = Windows.Forms.MouseButtons.Right) Then
'            p.rightMouseDown = True
'        End If
'    End Sub

'    Private Sub frmMain_MouseMove(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
'        If (Not IsNothing(p)) Then
'            Dim c As Camera = p.Cam
'            p.mouseX = Math.Floor((e.X / Tile.TileSize) + c.X)
'            p.mouseY = Math.Floor((e.Y / Tile.TileSize) + c.Y)
'        End If

'        Me.X = e.X
'        Me.Y = e.Y
'    End Sub

'    Private Sub frmMain_MouseUp(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp

'        If (e.Button = Windows.Forms.MouseButtons.Left) Then
'            p.leftMouseDown = False
'        ElseIf (e.Button = Windows.Forms.MouseButtons.Right) Then
'            p.rightMouseDown = False
'        End If
'    End Sub

'    Private Sub MouseWheelScroll(sender As Object, e As MouseEventArgs)
'        If (e.Delta > 0) Then
'            p.inventory.Up()
'        Else
'            p.inventory.Down()
'        End If
'    End Sub

'    Private Sub frmMain_Resize(sender As System.Object, e As System.EventArgs) Handles MyBase.Resize
'        Camera.Vision = New Size(Me.Size.Width / 16, Me.Size.Height / 16)
'        If (Not IsNothing(p)) Then p.Cam.Update(p.X, p.Y)
'    End Sub

'End Class
